/**
 * 可视化编辑器组合式函数
 * 处理网站元素选择、iframe 通信等逻辑
 */

import { ref, onMounted, onUnmounted, type Ref } from 'vue'

export interface SelectedElement {
  id: string
  tagName: string
  className: string
  textContent: string
  attributes: Record<string, string>
  xpath: string
  selector: string
}

export function useVisualEditor(
  iframeRef: Ref<HTMLIFrameElement | undefined>,
  onIframeReady?: () => void
) {
  // 编辑模式状态
  const isEditMode = ref(false)

  // 选中的元素列表
  const selectedElements = ref<SelectedElement[]>([])

  // iframe 是否已加载
  const iframeLoaded = ref(false)

  // 进入编辑模式
  const enterEditMode = () => {
    if (!iframeRef.value) {
      console.warn('iframe 引用不存在，无法进入编辑模式')
      return
    }


    isEditMode.value = true

    // 尝试注入脚本（可能需要多次尝试）
    const attemptInject = (attempts = 0) => {
      if (attempts > 5) {
        console.warn('脚本注入失败，已达到最大尝试次数')
        return
      }

      try {
        injectVisualEditorScript()

        // 等待一下再发送消息
        setTimeout(() => {
          sendMessageToIframe({
            type: 'ENTER_EDIT_MODE'
          })
        }, 200)


      } catch (error) {
        console.warn(`脚本注入尝试 ${attempts + 1} 失败，${500}ms 后重试:`, error)
        setTimeout(() => {
          attemptInject(attempts + 1)
        }, 500)
      }
    }

    attemptInject()
  }

  // 退出编辑模式
  const exitEditMode = () => {
    isEditMode.value = false

    // 向 iframe 发送退出编辑模式的消息
    sendMessageToIframe({
      type: 'EXIT_EDIT_MODE'
    })
  }

  // 清除选中的元素
  const clearSelectedElements = () => {

    selectedElements.value = []

    // 向 iframe 发送清除选中元素的消息
    sendMessageToIframe({
      type: 'CLEAR_SELECTED_ELEMENTS'
    })

  }

  // 移除指定的选中元素
  const removeSelectedElement = (elementId: string) => {

    selectedElements.value = selectedElements.value.filter(el => el.id !== elementId)


    // 向 iframe 发送移除元素的消息
    sendMessageToIframe({
      type: 'REMOVE_SELECTED_ELEMENT',
      payload: { elementId }
    })

  }

  // 高亮指定元素（用于悬浮效果）
  const highlightElement = (elementId: string, isHighlight: boolean) => {
    sendMessageToIframe({
      type: 'HIGHLIGHT_ELEMENT',
      payload: { elementId, isHighlight }
    })
  }

  // 向 iframe 发送消息
  const sendMessageToIframe = (message: any) => {
    if (!iframeRef.value?.contentWindow) {
      console.warn('iframe contentWindow 不可用')
      return
    }

    try {
      iframeRef.value.contentWindow.postMessage(message, '*')
    } catch (error) {
      console.error('发送消息到 iframe 失败:', error)
    }
  }

  // 注入可视化编辑器脚本到 iframe
  const injectVisualEditorScript = () => {
    if (!iframeRef.value?.contentDocument) {
      console.warn('⚠️ iframe contentDocument 不可用，尝试使用内联脚本')
      // 如果无法访问 contentDocument，尝试直接发送消息
      setTimeout(() => {
        sendMessageToIframe({
          type: 'ENTER_EDIT_MODE'
        })
      }, 1000)
      return
    }

    const doc = iframeRef.value.contentDocument

    // 检查脚本是否已存在
    if (doc.getElementById('visual-editor-script') || doc.getElementById('visual-editor-inline-script')) {

      return
    }

    // 尝试加载外部脚本，如果失败则使用内联脚本
    const script = doc.createElement('script')
    script.id = 'visual-editor-script'

    // 构造完整的脚本URL
    const scriptUrl = `${window.location.origin}/visual-editor.js`
    script.src = scriptUrl

    script.onload = () => {

    }

    script.onerror = () => {
      console.warn('⚠️ 外部脚本加载失败，使用内联脚本')
      // 如果外部脚本加载失败，注入内联脚本
      injectInlineScript(doc)
    }

    // 添加到文档头部
    if (doc.head) {
      doc.head.appendChild(script)
    } else {
      // 如果没有 head 标签，等待DOM加载完成
      doc.addEventListener('DOMContentLoaded', () => {
        if (doc.head) {
          doc.head.appendChild(script)
        } else {
          console.warn('⚠️ 无法找到 head 标签，使用内联脚本')
          injectInlineScript(doc)
        }
      })
    }
  }

  // 注入内联脚本（备用方案）
  const injectInlineScript = (doc: Document) => {
    const inlineScript = doc.createElement('script')
    inlineScript.id = 'visual-editor-inline-script'
    inlineScript.textContent = `
      // 优化版的可视化编辑器脚本
      (function() {
        let isEditMode = false;
        let hoverTooltip = null;
        let selectedElementsMap = new Map(); // 存储选中元素及其原始样式

        // 创建悬浮提示元素
        const createTooltip = () => {
          if (hoverTooltip) return hoverTooltip;

          hoverTooltip = document.createElement('div');
          hoverTooltip.className = 'visual-editor-tooltip';
          hoverTooltip.style.cssText = \`
            position: absolute;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 10000;
            pointer-events: none;
            max-width: 300px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            white-space: nowrap;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.4;
            display: none;
          \`;

          document.body.appendChild(hoverTooltip);
          return hoverTooltip;
        };

        // 显示悬浮提示
        const showTooltip = (element, event) => {
          const tooltip = createTooltip();

          const tagName = element.tagName.toLowerCase();
          const className = element.className ? \`.\${element.className.split(' ').join('.')}\` : '';
          const id = element.id ? \`#\${element.id}\` : '';
          const textContent = element.textContent?.trim().substring(0, 50) || '';

          let content = \`<span style="color: #4fc3f7;">\${tagName}</span>\`;
          if (id) content += \`<span style="color: #81c784;">\${id}</span>\`;
          if (className) content += \`<span style="color: #ffb74d;">\${className}</span>\`;
          if (textContent) content += \`<br><span style="color: #e0e0e0;">"\${textContent}\${textContent.length >= 50 ? '...' : ''}"</span>\`;

          tooltip.innerHTML = content;
          tooltip.style.display = 'block';

          const rect = element.getBoundingClientRect();
          let left = event.pageX + 10;
          let top = event.pageY - 10;

          if (left + 300 > window.innerWidth) {
            left = event.pageX - 310;
          }
          if (top < 0) {
            top = event.pageY + 20;
          }

          tooltip.style.left = left + 'px';
          tooltip.style.top = top + 'px';
        };

        // 隐藏悬浮提示
        const hideTooltip = () => {
          if (hoverTooltip) {
            hoverTooltip.style.display = 'none';
          }
        };

        // 禁用交互元素
        const disableInteractiveElements = () => {
          const interactiveElements = document.querySelectorAll('input, button, select, textarea, a[href], [onclick], [tabindex]');
          interactiveElements.forEach(element => {
            // 保存原始状态
            element.dataset.originalPointerEvents = element.style.pointerEvents || '';
            element.dataset.originalTabIndex = element.tabIndex || '';

            // 禁用交互
            element.style.pointerEvents = 'none';
            element.tabIndex = -1;

            // 添加视觉提示
            element.style.opacity = '0.6';
            element.dataset.visualEditorDisabled = 'true';
          });
        };

        // 恢复交互元素
        const enableInteractiveElements = () => {
          const disabledElements = document.querySelectorAll('[data-visual-editor-disabled="true"]');
          disabledElements.forEach(element => {
            // 恢复原始状态
            element.style.pointerEvents = element.dataset.originalPointerEvents || '';
            element.tabIndex = element.dataset.originalTabIndex ? parseInt(element.dataset.originalTabIndex) : 0;

            // 移除视觉提示
            element.style.opacity = '';

            // 清理数据属性
            delete element.dataset.originalPointerEvents;
            delete element.dataset.originalTabIndex;
            delete element.dataset.visualEditorDisabled;
          });
        };

        // 保存元素原始样式
        const saveOriginalStyles = (element) => {
          if (!selectedElementsMap.has(element)) {
            const originalStyles = {
              outline: element.style.outline || '',
              outlineOffset: element.style.outlineOffset || '',
              backgroundColor: element.style.backgroundColor || '',
              boxShadow: element.style.boxShadow || ''
            };
            selectedElementsMap.set(element, originalStyles);
          }
        };

        // 恢复元素原始样式
        const restoreOriginalStyles = (element) => {
          const originalStyles = selectedElementsMap.get(element);
          if (originalStyles) {

            element.style.outline = originalStyles.outline;
            element.style.outlineOffset = originalStyles.outlineOffset;
            element.style.backgroundColor = originalStyles.backgroundColor;
            element.style.boxShadow = originalStyles.boxShadow;

            // 重置所有可能的修改
            element.style.transform = '';
            element.style.transition = '';
            element.style.zIndex = '';

            element.classList.remove('visual-editor-hover', 'visual-editor-selected');
            selectedElementsMap.delete(element);

          } else {
            console.warn('⚠️ 未找到元素的原始样式信息');
            // 即使没有保存的样式，也要清理可能的修改
            element.style.outline = '';
            element.style.outlineOffset = '';
            element.style.transform = '';
            element.style.transition = '';
            element.style.zIndex = '';
            element.classList.remove('visual-editor-hover', 'visual-editor-selected');
          }
        };

        const handleMessage = (event) => {
          const { type, payload } = event.data;
          if (type === 'ENTER_EDIT_MODE') {
            enterEditMode();
          } else if (type === 'EXIT_EDIT_MODE') {
            exitEditMode();
          } else if (type === 'CLEAR_SELECTED_ELEMENTS') {
            clearAllSelectedElements();
          } else if (type === 'REMOVE_SELECTED_ELEMENT') {
            removeSelectedElementById(payload?.elementId);
          } else if (type === 'HIGHLIGHT_ELEMENT') {
            highlightElementById(payload?.elementId, payload?.isHighlight);
          }
        };

        const enterEditMode = () => {
          isEditMode = true;

          // 设置鼠标为pointer样式
          document.body.style.cursor = 'pointer';
          document.body.style.setProperty('cursor', 'pointer', 'important');

          // 禁用iframe内的交互元素
          disableInteractiveElements();

          document.addEventListener('mouseover', handleMouseOver, true);
          document.addEventListener('mouseout', handleMouseOut, true);
          document.addEventListener('mousemove', handleMouseMove, true);
          document.addEventListener('click', handleClick, true);

        };

        const exitEditMode = () => {
          isEditMode = false;

          // 恢复原始鼠标样式
          document.body.style.cursor = '';
          document.body.style.removeProperty('cursor');
          // 移除蓝色主题类
          document.body.classList.remove('visual-editor-blue-cursor');

          // 恢复交互元素
          enableInteractiveElements();

          document.removeEventListener('mouseover', handleMouseOver, true);
          document.removeEventListener('mouseout', handleMouseOut, true);
          document.removeEventListener('mousemove', handleMouseMove, true);
          document.removeEventListener('click', handleClick, true);
          clearAllStyles();
          hideTooltip();

        };

        const clearAllStyles = () => {
          selectedElementsMap.forEach((originalStyles, element) => {
            restoreOriginalStyles(element);
          });
          selectedElementsMap.clear();

          document.querySelectorAll('.visual-editor-hover').forEach(el => {
            el.classList.remove('visual-editor-hover');
            el.style.outline = '';
            el.style.outlineOffset = '';
          });
        };

        const clearAllSelectedElements = () => {
          selectedElementsMap.forEach((originalStyles, element) => {
            restoreOriginalStyles(element);
          });
          selectedElementsMap.clear();
        };

        const removeSelectedElementById = (elementId) => {

          const element = document.querySelector(\`[data-visual-editor-id="\${elementId}"]\`);
          if (element) {

            restoreOriginalStyles(element);
            element.removeAttribute('data-visual-editor-id');

          } else {
            console.warn('⚠️ 未找到对应的选中元素:', elementId);
          }
        };

        const highlightElementById = (elementId, isHighlight) => {
          const element = document.querySelector(\`[data-visual-editor-id="\${elementId}"]\`);
          if (element) {
            if (isHighlight) {
              // 添加高亮效果
              element.style.transform = 'scale(1.02)';
              element.style.transition = 'all 0.2s ease';
              element.style.zIndex = '9999';
              // 增强边框效果
              element.style.outline = '3px solid #ff7a00';
              element.style.outlineOffset = '3px';
            } else {
              // 移除高亮效果
              element.style.transform = '';
              element.style.zIndex = '';
              // 恢复原有边框
              element.style.outline = '2px solid #52c41a';
              element.style.outlineOffset = '2px';
            }
          }
        };

        const handleMouseOver = (event) => {
          if (!isEditMode) return;
          const element = event.target;
          if (element === document.body || element === document.documentElement) return;

          if (!element.classList.contains('visual-editor-selected')) {
            element.style.outline = '2px dashed #1890ff';
            element.style.outlineOffset = '2px';
            element.classList.add('visual-editor-hover');
          }
        };

        const handleMouseOut = (event) => {
          if (!isEditMode) return;
          const element = event.target;

          if (!element.classList.contains('visual-editor-selected')) {
            element.style.outline = '';
            element.style.outlineOffset = '';
          }
          element.classList.remove('visual-editor-hover');
          hideTooltip();
        };

        const handleMouseMove = (event) => {
          if (!isEditMode) return;
          const element = event.target;
          if (element === document.body || element === document.documentElement) return;

          if (element.classList.contains('visual-editor-hover') && !element.classList.contains('visual-editor-selected')) {
            showTooltip(element, event);
          }
        };

        const handleClick = (event) => {
          if (!isEditMode) return;
          event.preventDefault();
          event.stopPropagation();

          const element = event.target;
          if (element === document.body || element === document.documentElement) return;

          // 如果已经选中，则取消选中
          if (element.classList.contains('visual-editor-selected')) {
            const elementId = element.getAttribute('data-visual-editor-id');


            restoreOriginalStyles(element);
            element.removeAttribute('data-visual-editor-id');
            hideTooltip();

            // 通知父窗口移除该元素
            if (elementId) {
              window.parent.postMessage({
                type: 'ELEMENT_DESELECTED',
                payload: { elementId }
              }, '*');

            }

            return;
          }

          // 保存原始样式并应用选中样式
          saveOriginalStyles(element);
          element.style.outline = '2px solid #52c41a';
          element.style.outlineOffset = '2px';

          // 使用 box-shadow 而不是 background，避免覆盖原有背景
          const originalBoxShadow = element.style.boxShadow || '';
          element.style.boxShadow = originalBoxShadow + (originalBoxShadow ? ', ' : '') + 'inset 0 0 0 1000px rgba(82, 196, 26, 0.05)';

          element.classList.add('visual-editor-selected');

          // 生成唯一ID
          const elementId = \`element_\${Date.now()}_\${Math.random().toString(36).substr(2, 9)}\`;
          element.setAttribute('data-visual-editor-id', elementId);

          // 发送选中信息给父窗口
          window.parent.postMessage({
            type: 'ELEMENT_SELECTED',
            payload: {
              id: elementId,
              tagName: element.tagName.toLowerCase(),
              className: element.className || '',
              textContent: element.textContent?.trim().substring(0, 100) || '',
              selector: element.tagName.toLowerCase() + (element.className ? '.' + element.className.split(' ').join('.') : ''),
              xpath: getXPath(element)
            }
          }, '*');

          hideTooltip();

        };

        // 生成 XPath
        const getXPath = (element) => {
          if (element.id) {
            return \`//*[@id="\${element.id}"]\`;
          }

          let path = '';
          while (element && element.nodeType === Node.ELEMENT_NODE) {
            let index = 0;
            let sibling = element.previousSibling;
            while (sibling) {
              if (sibling.nodeType === Node.ELEMENT_NODE && sibling.nodeName === element.nodeName) {
                index++;
              }
              sibling = sibling.previousSibling;
            }

            const tagName = element.nodeName.toLowerCase();
            const pathIndex = index > 0 ? \`[\${index + 1}]\` : '';
            path = \`/\${tagName}\${pathIndex}\${path}\`;

            element = element.parentNode;
          }

          return path;
        };

        window.addEventListener('message', handleMessage);
        window.parent.postMessage({ type: 'IFRAME_LOADED' }, '*');

      })();
    `

    if (doc.head) {
      doc.head.appendChild(inlineScript)
    } else if (doc.body) {
      doc.body.appendChild(inlineScript)
    }


  }

  // 处理来自 iframe 的消息
  const handleIframeMessage = (event: MessageEvent) => {
    // 放宽安全检查，允许同源和本地消息
    const isValidOrigin = event.origin === window.location.origin ||
                         event.origin === 'null' || // file:// 协议
                         event.origin.includes('localhost') ||
                         event.origin.includes('127.0.0.1')

    if (!isValidOrigin) {

      return
    }

    // 检查消息数据是否存在且为对象
    if (!event.data || typeof event.data !== 'object') {
      // 忽略非对象类型的消息（如字符串、数字等）
      return
    }

    const { type, payload } = event.data

    // 如果没有type字段，说明不是我们期望的消息格式
    if (!type) {
      return
    }

    switch (type) {
      case 'IFRAME_LOADED':
        iframeLoaded.value = true

        // iframe 加载完成后，注入可视化编辑器脚本
        setTimeout(() => {
          injectVisualEditorScript()
          // 通知外部 iframe 已准备就绪
          if (onIframeReady) {

            onIframeReady()
          }
        }, 100)
        break

      case 'ELEMENT_SELECTED':
        handleElementSelected(payload)
        break

      case 'ELEMENT_DESELECTED':
        handleElementDeselected(payload)
        break

      case 'ELEMENT_HOVER':
        // 可以在这里处理元素悬浮事件

        break

      default:

    }
  }

  // 处理元素被选中
  const handleElementSelected = (elementData: any) => {
    const element: SelectedElement = {
      id: elementData.id || generateElementId(), // 使用传入的 ID，如果没有则生成新的
      tagName: elementData.tagName,
      className: elementData.className || '',
      textContent: elementData.textContent?.trim() || '',
      attributes: elementData.attributes || {},
      xpath: elementData.xpath || '',
      selector: elementData.selector || ''
    }

    // 检查是否已经选中了相同的元素
    const exists = selectedElements.value.some(el =>
      el.id === element.id || (el.selector === element.selector && el.xpath === element.xpath)
    )

    if (!exists) {
      selectedElements.value.push(element)

    } else {

    }
  }

  // 处理元素被取消选中
  const handleElementDeselected = (payload: any) => {
    if (payload?.elementId) {

      selectedElements.value = selectedElements.value.filter(el => el.id !== payload.elementId)

    }
  }  // 生成元素唯一ID
  const generateElementId = () => {
    return `element_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  // 获取选中元素的描述文本（用于添加到提示词中）
  const getSelectedElementsPrompt = () => {
    if (selectedElements.value.length === 0) {
      return ''
    }

    const elementsDescription = selectedElements.value.map(element => {
      // 构建原始HTML元素
      const tagName = element.tagName.toLowerCase()

      // 获取原始类名（过滤掉visual-editor相关的临时类名）
      const originalClasses = element.className ?
        element.className.trim().split(/\s+/)
          .filter(cls => cls && !cls.startsWith('visual-editor-'))
          .join(' ') : ''

      // 构建原始HTML标签
      let originalHtml = `<${tagName}`
      if (originalClasses) {
        originalHtml += ` class="${originalClasses}"`
      }
      originalHtml += `>${element.textContent || ''}</${tagName}>`

      // 构建结构化信息
      const parts = []
      parts.push(`标签: ${element.tagName}`)
      parts.push(`文本: ${element.textContent || ''}`)
      parts.push(`类名：${originalClasses || '无'}`)
      parts.push(`选择器: ${element.selector}`)

      return `\n需要修改的元素：[${originalHtml}]\n${parts.join(', ')}`
    }).join('\n')

    const promptText = `${elementsDescription}\n请根据用户的需求和选中的元素信息进行相应的修改。`



    return promptText
  }  // 监听 iframe 消息
  onMounted(() => {
    window.addEventListener('message', handleIframeMessage)
  })

  onUnmounted(() => {
    window.removeEventListener('message', handleIframeMessage)
  })

  return {
    isEditMode,
    selectedElements,
    iframeLoaded,
    enterEditMode,
    exitEditMode,
    clearSelectedElements,
    removeSelectedElement,
    highlightElement,
    getSelectedElementsPrompt,
    handleIframeMessage
  }
}
